#include <iostream>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>

using namespace std;

void SetNonBlock(int fd)
{
    int flag = fcntl(fd, F_GETFL);      // 获得文件状态标志
    if (flag < 0)       // 获取失败
    {
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, flag | O_NONBLOCK);      // 获取成功，设置非阻塞
}

int main()
{
    SetNonBlock(0);
    char buff[1024];
    while (true)
    {
        ssize_t sz = read(0, buff, sizeof(buff) - 1);
        if (sz > 0)
        {
            buff[sz] = 0;
            cout << "get a message: " << buff << endl;
        }
        else if (sz == 0)
        {
            cout << "quit" << endl;
        }
        else
        {
            if (errno == EWOULDBLOCK)
            {
                cout << "nonblock, there is no ready, try again..." << endl;
                sleep(1);
            }
            else
                cout << "read error" << errno << " error string: " << strerror(errno) << endl;
        }
        // cout << "snowdragon" << endl;
    }

    return 0;
}